package com.yunkaweilai.android.fragment.operation.room;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.operation.consumption.room.RoomInfoActivity;
import com.yunkaweilai.android.base.BaseFragment;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.SimpleInterface;
import com.yunkaweilai.android.interfaces.StringTwoInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.operation.room.RoomListModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.dialog.room.GuadanTurnRoomDialog;
import com.yunkaweilai.android.view.dialog.room.OpenRoomDialog;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * 房台列表
 * Created by Administrator on 2017/7/27.
 */

public class RoomTypeListFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate, SimpleInterface {

    Unbinder unbinder;
    @BindView(R.id.id_gridView)
    GridView idGridView;
    @BindView(R.id.content_view)
    BGARefreshLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    private String category_id;
    private ArrayList<RoomListModel.DataBean.ListBean> shoplist = new ArrayList<>();
    private CommonAdapter<RoomListModel.DataBean.ListBean> adapter;
    private String type = "1";
    private String gid = "0";
    private String title = "";
    public static RoomTypeListFragment getInstentce(String category_id,String type,String gid) {
        RoomTypeListFragment fragment = new RoomTypeListFragment();
        fragment.category_id = category_id;
        fragment.type = type;
        fragment.gid = gid;
        return fragment;
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_room_list;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initRefreshLayout(contentView,this,true);
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onShopEvent(Event.TypeEvent event) {
        if (event != null) {
            if (event.type == CommonConstants.GUADAN_ROOM_LIST_REFRESH) {
                if (event.flag) {
                    idMultipleStatusView.showLoading();
                    initHttp();
                }
            }
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initAdapter();
        initClick();
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp();
            }
        });
        initHttp();
    }


    private boolean initHttp() {
        HttpRequest.postUrl(Api.ROOM_LIST)
                .addParams("category_id", category_id)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        endRefreshOrLoad(true);
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            RoomListModel roomListModel = gson.fromJson(json, RoomListModel.class);
                            shoplist.clear();
                            if (roomListModel.getData().getList()!= null && roomListModel.getData().getList().size() != 0) {
                                shoplist.addAll(roomListModel.getData().getList());
                                adapter.notifyDataSetChanged();
                                if (idMultipleStatusView != null) {
                                    idMultipleStatusView.showContent();
                                }
                            } else {
                                    if (idMultipleStatusView != null) {
                                        idMultipleStatusView.showEmpty();
                                    }
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                    }
                });
        return true;
    }

    private void initClick() {
        idGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RoomListModel.DataBean.ListBean listBean = shoplist.get(position);

                if ("1".equals(type)){
                    if ("0".equals(listBean.get_status())){
                        showToast("停用中");
                    }else{
                        if ("0".equals(listBean.getIs_useing())){
                            OpenRoomDialog dialog = new OpenRoomDialog(mAc,listBean.getTitle()+"",listBean.getRemark(),listBean.getId(),listBean.getIs_fangfei());
                            dialog.show();
                        }else{
                            RoomInfoActivity.actionStart(mAc,listBean.getLately_gid(),listBean.getTitle(),true);
                        }
                    }
                }else if ("2".equals(type)){
                    if ("0".equals(listBean.get_status())){
                        showToast("该房台不可转台");
                    }else{
                        if ("0".equals(listBean.getIs_useing())){
                            title = listBean.getTitle();
                            GuadanTurnRoomDialog dialog = new GuadanTurnRoomDialog(mAc,gid,listBean.getTitle(),listBean.getRemark(),listBean.getId(),RoomTypeListFragment.this);
                            dialog.show();

                        }else{
                            showToast("该房台不可转台");
                        }
                    }
                }

            }
        });

    }

    private void initAdapter() {
        adapter = new CommonAdapter<RoomListModel.DataBean.ListBean>(mAc, R.layout.item_grid_room, shoplist) {
                @Override
            protected void convert(ViewHolder viewHolder, RoomListModel.DataBean.ListBean item, int position) {
                    viewHolder.setText(R.id.id_tv_name,item.getTitle()+"");
                    TextView idTvStatus = viewHolder.getView(R.id.id_tv_status);
                    TextView idTvPrice = viewHolder.getView(R.id.id_tv_price);
                    LinearLayout idLlayoutBg = viewHolder.getView(R.id.id_llayout_bg);

                    if("0".equals(item.get_status())){
                        idTvStatus.setText("维护");
                        idTvPrice.setVisibility(View.GONE);
                        idLlayoutBg.setBackgroundResource(R.drawable.shape_room_maintain);
                    }else{
                        if ("1".equals(item.getIs_useing())){
                            idTvStatus.setText("进行");
                            if ("2".equals(item.getOrder_status())){
                                idTvPrice.setText("已结账请关台");
                            }else{
                                idTvPrice.setText("已消费:" + item.getPayment());
                            }
                            idTvPrice.setVisibility(View.VISIBLE);
                            idLlayoutBg.setBackgroundResource(R.drawable.shape_room_conduct);
                        }else{
                            idTvStatus.setText("空闲");
                            idTvPrice.setVisibility(View.GONE);
                            idLlayoutBg.setBackgroundResource(R.drawable.shape_room_free);
                        }
                    }
                    if (StringUtils.isEmpty(item.getRemark())){
                        viewHolder.setText(R.id.id_tv_remarks,"");
                    }else{
                        viewHolder.setText(R.id.id_tv_remarks,item.getRemark());

                    }
                }
        };
        idGridView.setAdapter(adapter);

    }

    /**
     * 结束刷新组件
     *
     * @param refresh
     */
    private void endRefreshOrLoad(boolean refresh) {
        if (refresh) {
            if (contentView != null){
                contentView.endRefreshing();
            }
        } else {
            if (contentView != null){
                contentView.endLoadingMore();
            }
        }
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        initHttp();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        return false;
    }


    @Override
    public void nothing() {
        RoomInfoActivity.actionStart(mAc,gid,title,true);
    }
}
